import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useLanguage } from '@kernelproxy/i18n';
import { 
  ArrowLeft,
  Send,
  Paperclip,
  User,
  Clock,
  AlertCircle,
  CheckCircle
} from 'lucide-react';

const TicketDetail = () => {
  const { ticketId } = useParams();
  const navigate = useNavigate();
  const { language } = useLanguage();
  const [newMessage, setNewMessage] = useState('');

  // Mock ticket data - in real app, fetch based on ticketId
  const ticket = {
    id: ticketId || 'TKT-001234',
    subject: language === 'zh-CN' ? 'API连接问题' : 'API Connection Issue',
    category: language === 'zh-CN' ? '技术支持' : 'Technical',
    priority: 'high',
    status: 'in-progress',
    createdAt: '2025-10-08 14:30',
    lastUpdate: '2025-10-09 10:30',
    messages: [
      {
        id: '1',
        sender: 'user',
        senderName: 'You',
        message: language === 'zh-CN' 
          ? '我在使用API时遇到连接超时的问题，已经尝试了多次但都失败了。错误代码是 ETIMEDOUT。请帮忙查看一下。' 
          : 'I am experiencing connection timeout issues when using the API. I have tried multiple times but it keeps failing. The error code is ETIMEDOUT. Please help.',
        timestamp: '2025-10-08 14:30',
        attachments: []
      },
      {
        id: '2',
        sender: 'support',
        senderName: language === 'zh-CN' ? '技术支持团队' : 'Support Team',
        message: language === 'zh-CN'
          ? '您好，感谢您联系我们。我们正在调查这个问题。请问您使用的是哪个地区的代理服务器？另外，能否提供一下完整的错误日志？'
          : 'Hello, thank you for contacting us. We are investigating this issue. Which region proxy server are you using? Also, could you provide the complete error log?',
        timestamp: '2025-10-08 16:45',
        attachments: []
      },
      {
        id: '3',
        sender: 'user',
        senderName: 'You',
        message: language === 'zh-CN'
          ? '我使用的是美国东部的服务器。错误日志已经附在下面了。'
          : 'I am using the US East server. The error log is attached below.',
        timestamp: '2025-10-09 09:15',
        attachments: ['error_log.txt']
      },
      {
        id: '4',
        sender: 'support',
        senderName: language === 'zh-CN' ? '技术支持团队' : 'Support Team',
        message: language === 'zh-CN'
          ? '我们已经找到问题所在。美国东部的某台服务器出现了网络问题，我们已经将流量切换到备用服务器。现在应该可以正常使用了，请您再试一次。'
          : 'We have found the issue. One of the servers in US East experienced network problems. We have switched the traffic to a backup server. It should work normally now, please try again.',
        timestamp: '2025-10-09 10:30',
        attachments: []
      }
    ]
  };

  const getStatusBadge = () => {
    const badges = {
      'open': {
        bg: 'bg-blue-100 dark:bg-blue-900/30',
        text: 'text-blue-800 dark:text-blue-400',
        label: language === 'zh-CN' ? '待处理' : 'Open',
        icon: <AlertCircle size={14} />
      },
      'in-progress': {
        bg: 'bg-yellow-100 dark:bg-yellow-900/30',
        text: 'text-yellow-800 dark:text-yellow-400',
        label: language === 'zh-CN' ? '处理中' : 'In Progress',
        icon: <Clock size={14} />
      },
      'resolved': {
        bg: 'bg-green-100 dark:bg-green-900/30',
        text: 'text-green-800 dark:text-green-400',
        label: language === 'zh-CN' ? '已解决' : 'Resolved',
        icon: <CheckCircle size={14} />
      },
      'closed': {
        bg: 'bg-gray-100 dark:bg-gray-700',
        text: 'text-gray-800 dark:text-gray-200',
        label: language === 'zh-CN' ? '已关闭' : 'Closed',
        icon: <CheckCircle size={14} />
      }
    };
    return badges[ticket.status as keyof typeof badges];
  };

  const getPriorityColor = () => {
    const colors = {
      'low': 'text-gray-600 dark:text-gray-400',
      'medium': 'text-blue-600 dark:text-blue-400',
      'high': 'text-orange-600 dark:text-orange-400',
      'urgent': 'text-red-600 dark:text-red-400'
    };
    return colors[ticket.priority as keyof typeof colors];
  };

  const getPriorityLabel = () => {
    const labels = {
      'low': language === 'zh-CN' ? '低' : 'Low',
      'medium': language === 'zh-CN' ? '中' : 'Medium',
      'high': language === 'zh-CN' ? '高' : 'High',
      'urgent': language === 'zh-CN' ? '紧急' : 'Urgent'
    };
    return labels[ticket.priority as keyof typeof labels];
  };

  const handleSendMessage = (e: React.FormEvent) => {
    e.preventDefault();
    if (newMessage.trim()) {
      // Handle sending message
      console.log('Sending message:', newMessage);
      setNewMessage('');
    }
  };

  const statusBadge = getStatusBadge();

  return (
    <div className="p-6 max-w-5xl mx-auto">
      {/* Header */}
      <div className="mb-6">
        <button
          onClick={() => navigate('/dashboard/support')}
          className="flex items-center gap-2 text-blue-600 dark:text-blue-400 hover:underline mb-4"
        >
          <ArrowLeft size={18} />
          {language === 'zh-CN' ? '返回工单列表' : 'Back to Tickets'}
        </button>
        
        <div className="bg-white dark:bg-gray-800 rounded-lg p-6 border border-gray-200 dark:border-gray-700">
          <div className="flex items-start justify-between mb-4">
            <div className="flex-1">
              <div className="flex items-center gap-3 mb-2">
                <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
                  {ticket.subject}
                </h1>
                <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium ${statusBadge.bg} ${statusBadge.text}`}>
                  {statusBadge.icon}
                  {statusBadge.label}
                </span>
              </div>
              <div className="flex items-center gap-4 text-sm text-gray-600 dark:text-gray-400">
                <span className="font-mono">{ticket.id}</span>
                <span>•</span>
                <span>{ticket.category}</span>
                <span>•</span>
                <span className={`font-medium ${getPriorityColor()}`}>
                  {language === 'zh-CN' ? '优先级: ' : 'Priority: '}{getPriorityLabel()}
                </span>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4 pt-4 border-t border-gray-200 dark:border-gray-700">
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">
                {language === 'zh-CN' ? '创建时间' : 'Created'}
              </p>
              <p className="text-sm text-gray-900 dark:text-white">{ticket.createdAt}</p>
            </div>
            <div>
              <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">
                {language === 'zh-CN' ? '最后更新' : 'Last Updated'}
              </p>
              <p className="text-sm text-gray-900 dark:text-white">{ticket.lastUpdate}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Messages */}
      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 mb-6">
        <div className="p-6 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '对话记录' : 'Conversation'}
          </h2>
        </div>
        
        <div className="p-6 space-y-6">
          {ticket.messages.map((msg) => (
            <div key={msg.id} className={`flex gap-4 ${msg.sender === 'user' ? 'flex-row-reverse' : ''}`}>
              <div className={`flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center ${
                msg.sender === 'user' 
                  ? 'bg-blue-600' 
                  : 'bg-purple-600'
              }`}>
                <User className="w-5 h-5 text-white" />
              </div>
              
              <div className={`flex-1 ${msg.sender === 'user' ? 'items-end' : 'items-start'} flex flex-col`}>
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-sm font-medium text-gray-900 dark:text-white">
                    {msg.senderName}
                  </span>
                  <span className="text-xs text-gray-500 dark:text-gray-400">
                    {msg.timestamp}
                  </span>
                </div>
                
                <div className={`p-4 rounded-lg max-w-2xl ${
                  msg.sender === 'user'
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white'
                }`}>
                  <p className="text-sm whitespace-pre-wrap">{msg.message}</p>
                  
                  {msg.attachments && msg.attachments.length > 0 && (
                    <div className="mt-3 pt-3 border-t border-blue-500/20 dark:border-gray-600">
                      {msg.attachments.map((file, idx) => (
                        <div key={idx} className="flex items-center gap-2 text-sm">
                          <Paperclip size={14} />
                          <span>{file}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Reply Form */}
      {ticket.status !== 'closed' && (
        <div className="bg-white dark:bg-gray-800 rounded-lg p-6 border border-gray-200 dark:border-gray-700">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            {language === 'zh-CN' ? '回复' : 'Reply'}
          </h3>
          <form onSubmit={handleSendMessage} className="space-y-4">
            <textarea
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              rows={4}
              className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500"
              placeholder={language === 'zh-CN' ? '输入您的回复...' : 'Type your reply...'}
            />
            <div className="flex items-center justify-between">
              <input
                type="file"
                multiple
                className="text-sm text-gray-600 dark:text-gray-400"
              />
              <button
                type="submit"
                disabled={!newMessage.trim()}
                className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Send size={18} />
                {language === 'zh-CN' ? '发送' : 'Send'}
              </button>
            </div>
          </form>
        </div>
      )}

      {ticket.status === 'closed' && (
        <div className="bg-gray-50 dark:bg-gray-900/50 rounded-lg p-6 border border-gray-200 dark:border-gray-700 text-center">
          <p className="text-gray-600 dark:text-gray-400">
            {language === 'zh-CN' ? '此工单已关闭，无法继续回复。' : 'This ticket is closed and cannot be replied to.'}
          </p>
        </div>
      )}
    </div>
  );
};

export default TicketDetail;
